package controllers;

import dto.Language;
import models.Constants;
import models.Menu;
import models.crudsiena.SienaSupport;
import play.exceptions.TemplateNotFoundException;
import play.i18n.Lang;
import play.mvc.Before;
import play.mvc.With;
import services.TopicService;

import java.util.Collection;
import java.util.List;

/**
 * Created by Gipxy group
 * Date: 4/2/12
 */

@With(Secure.class)
public class Menus extends CRUD{
    @Before  (only = {"blank","show"})
    static void loadAllTopicCode() {
        Collection<String> allTopicCodes = TopicService.getAllTopicCodes();
        renderArgs.put("allTopicCodes", allTopicCodes);
        allTopicCodes.add("");

        Language[] allLanguages= Language.all;
        renderArgs.put("allLanguages", allLanguages);
        
        renderArgs.put("allMenus", new String[]{Constants.PRODUCT_MENU_KEY, Constants.APP_MENU_KEY});
    }

    public static void show(String id) {

        ObjectType type = ObjectType.get(getControllerClass());
        notFoundIfNull(type);
        SienaSupport object = type.findById(id);
        try {
            render(type, object);
        } catch (TemplateNotFoundException e) {
            render("CRUD/show.html", type, object);
        }
    }

    public static void list(int page, String filterField, String filterValue, String orderBy, String order) {
        //custom code, filter language
        /*
        filterField = Language.LANGUAGE_KEY;
        filterValue = Lang.get();
        orderBy = Language.LANGUAGE_KEY;

        ObjectType type = ObjectType.get(getControllerClass());
        notFoundIfNull(type);
        if (page < 1) {
            page = 1;
        }
        List<? extends SienaSupport> objects = type.findPage(page, filterField, filterValue, orderBy, order);
        Long count = type.count(filterField, filterValue);
        Long totalCount = type.count(null, null);
        try {
            render(type, objects, count, totalCount, page, orderBy, order);
        } catch (TemplateNotFoundException e) {
            render("CRUD/list.html", type, objects, count, totalCount, page, orderBy, order);
        }
        */
        ObjectType type = ObjectType.get(getControllerClass());
        Long count = type.count(filterField, filterValue);
        List<Menu> objects = Menu.all(Menu.class).filter(Language.LANGUAGE_KEY, Lang.get()).fetch();
        render(type, objects, count, objects.size(), page, orderBy, order);
    }
}
